package com.pick.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pick.admin.entity.SysRole;
import com.pick.admin.entity.SysRolePermission;
import com.pick.admin.entity.SysUserRole;
import com.pick.admin.mapper.SysRoleMapper;
import com.pick.admin.mapper.SysRolePermissionMapper;
import com.pick.admin.mapper.SysUserRoleMapper;
import com.pick.admin.service.SysRoleService;
import com.pick.base.common.PageQuery;
import cn.hutool.core.util.StrUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 系统角色服务实现类
 */
@Service
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole> implements SysRoleService {

    @Autowired
    private SysRolePermissionMapper rolePermissionMapper;

    @Autowired
    private SysUserRoleMapper userRoleMapper;

    @Override
    public IPage<SysRole> pageRoles(PageQuery pageQuery) {
        Page<SysRole> page = new Page<>(pageQuery.getCurrent(), pageQuery.getSize());
        LambdaQueryWrapper<SysRole> wrapper = new LambdaQueryWrapper<>();
        
        if (StrUtil.isNotBlank(pageQuery.getKeyword())) {
            wrapper.like(SysRole::getRoleName, pageQuery.getKeyword())
                    .or().like(SysRole::getRoleCode, pageQuery.getKeyword())
                    .or().like(SysRole::getDescription, pageQuery.getKeyword());
        }
        
        if (StrUtil.isNotBlank(pageQuery.getOrderBy())) {
            if ("ASC".equalsIgnoreCase(pageQuery.getOrder())) {
                wrapper.orderByAsc(SysRole::getId);
            } else {
                wrapper.orderByDesc(SysRole::getId);
            }
        } else {
            wrapper.orderByDesc(SysRole::getCreateTime);
        }
        
        return this.page(page, wrapper);
    }

    @Override
    public boolean createRole(SysRole role) {
        // 检查角色编码是否已存在
        long count = this.count(new LambdaQueryWrapper<SysRole>()
                .eq(SysRole::getRoleCode, role.getRoleCode()));
        if (count > 0) {
            throw new RuntimeException("角色编码已存在");
        }
        
        role.setStatus(1); // 默认启用
        return this.save(role);
    }

    @Override
    public boolean updateRole(SysRole role) {
        // 检查角色编码是否已存在（排除自己）
        long count = this.count(new LambdaQueryWrapper<SysRole>()
                .eq(SysRole::getRoleCode, role.getRoleCode())
                .ne(SysRole::getId, role.getId()));
        if (count > 0) {
            throw new RuntimeException("角色编码已存在");
        }
        
        return this.updateById(role);
    }

    @Override
    @Transactional
    public boolean deleteRole(Long roleId) {
        // 检查是否有用户使用该角色
        long userCount = userRoleMapper.selectCount(new LambdaQueryWrapper<SysUserRole>()
                .eq(SysUserRole::getRoleId, roleId));
        if (userCount > 0) {
            throw new RuntimeException("该角色下还有用户，无法删除");
        }
        
        // 删除角色权限关联
        rolePermissionMapper.delete(new LambdaQueryWrapper<SysRolePermission>()
                .eq(SysRolePermission::getRoleId, roleId));
        
        // 删除角色
        return this.removeById(roleId);
    }

    @Override
    @Transactional
    public boolean assignPermissions(Long roleId, List<Long> permissionIds) {
        // 删除原有权限
        rolePermissionMapper.delete(new LambdaQueryWrapper<SysRolePermission>()
                .eq(SysRolePermission::getRoleId, roleId));
        
        // 分配新权限
        if (permissionIds != null && !permissionIds.isEmpty()) {
            for (Long permissionId : permissionIds) {
                SysRolePermission rolePermission = new SysRolePermission();
                rolePermission.setRoleId(roleId);
                rolePermission.setPermissionId(permissionId);
                rolePermissionMapper.insert(rolePermission);
            }
        }
        
        return true;
    }

    @Override
    public List<Long> getRolePermissionIds(Long roleId) {
        List<SysRolePermission> rolePermissions = rolePermissionMapper.selectList(
                new LambdaQueryWrapper<SysRolePermission>()
                        .eq(SysRolePermission::getRoleId, roleId));
        
        return rolePermissions.stream()
                .map(SysRolePermission::getPermissionId)
                .collect(Collectors.toList());
    }
}